#include<stdio.h>
#include<unistd.h>
#include<assert.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#define ARGC 100
#define MAX 1024
#define SEP " "
int split(char *commandstr,char *argv[])
{
    assert(commandstr);
    assert(argv);
    argv[0]=strtok(commandstr,SEP);
    if(argv[0]==NULL) return -1;
    int i=1;
    while(1)
    {
        argv[i]=strtok(NULL,SEP);
        if(argv[i]==NULL) break;
        i++;
    }
    return 0;

}

void debugPrint(char*argv[])
{
    for(int i=0;argv[i]!=NULL;i++)
    {
        printf("%d: %s\n",i,argv[i]);
    }
}
void showEnv()
{
    extern char** environ;
    for(int i=0;environ[i];i++)
    {
        printf("%d:%s\n",i,environ[i]);
    }
}
int main()
{
    //extern char**environ;
    int last_exit=0;
    char myenv[32][256];
    int env_index=0;
    while(1)
    {
        char commandstr[MAX]={0};
        char*argv[ARGC]={NULL};
        printf("[zhenbailinzi@mymachine currpath]# ");
        fflush(stdout);
        char *s=fgets(commandstr,sizeof(commandstr),stdin);
        assert(s);
        (void)s;//保证在release方式发布的时候，因为去掉assert了，所以s就没有被使用，而带来的编译告警，什么都没做，但是充当一次使用
        //去掉\n
        //abcd\n\0
        commandstr[strlen(commandstr)-1]='\0';
        int n=split(commandstr,argv);
        if(n!=0)
        {
            continue;
        }
        
        //cd:让bash自己执行的命令：内建命令
        if(strcmp(argv[0],"cd")==0)
        {
            if(argv[1]!=NULL)chdir(argv[1]);
            continue;
        }
        else if(strcmp(argv[0],"export")==0)
        {
            if(argv[1]!=NULL)
            {
                strcpy(myenv[env_index],argv[1]);
                putenv(myenv[env_index++]);
            }
            continue;
        }
        else if(strcmp(argv[0],"env")==0)
        {
            showEnv();
            continue;
        }
        else if(strcmp(argv[0],"echo")==0)
        {
            const char *target_env = NULL;
            if(argv[1][0]=='$')
            {
                if(argv[1][1]=='?')
                {
                    printf("%d\n",last_exit);
                    continue;
                }
                else
                {
                    target_env=getenv(argv[1]+1);
                }
            }
            if(target_env!=NULL)printf("%s=%s\n",argv[1]+1,target_env);
            continue;
        }
        if(strcmp(argv[0],"ls")==0)
        {
            int pos=0;
            while(argv[pos])pos++;
            argv[pos++]=(char*)"--color=auto";
            argv[pos]=NULL;
        }
        //debugPrint(argv);
        pid_t id=fork();
        assert(id>=0);
        (void)id;
        if(id==0)
        {
            execvp(argv[0],argv);
            exit(1);
        }
        int status=0;
        pid_t ret=waitpid(id,&status,0);//第三个参数为0为阻塞等待。
        if(ret>0)
        {
            last_exit=WEXITSTATUS(status);
        }
        //printf("%s",commandstr);
    }
}
